<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>手写render</title>
    <style>
        .list{
            color: red;
        }
    </style>
  </head>
  <body>
    <div id="app"></div>
    <script>
      let data = {
        tag: "h2",
        props: {
          class: "myclass",
          name: "xxx",
        },
        method: {
          click: (e) => {
            console.log(e);
          },
        },
        children: [
          {
            tag: "li",
            props: {
              class: "list",
            },
            children: "4万面五星红旗挂上武汉街头",
          },
          {
            tag: "li",
            props: {
              class: "list",
            },
            children: "机场水门最高礼遇迎接烈士遗骸",
          },
        ],
      };
      const render = (option) => {
        let el = document.createElement(option.tag);
        let props = option?.props;
        if (props && typeof props === "object") {
          for (let key in props) {
            //给指定元素增加属性
            el.setAttribute(key, props[key]);
          }
        }
        let method = option?.method;
        if (method && typeof method === "object") {
          for (let key in method) {
            //给指定元素增加方法
            el.addEventListener(key, (e) => method[key](e));
          }
        }
        if (Array.isArray(option.children)) {
            option.children.forEach(e => {
                el.appendChild(render(e))
            });
        } else {
          el.textContent = option.children;
        }
        return el;
      };
      app.appendChild(render(data));
    </script>
  </body>
</html>
